<?php defined('SYSPATH') or die('No direct script access.');

class form extends form_Core {
    public static function yesNoComboBox($data, $selectedValue, $extra=NULL) {
        $options = array(
            0 => text::get('application.boolean-no'),
            1 => text::get('application.boolean-yes')
        );
        return form::dropdown($data, $options, $selectedValue, $extra);
    }

    public static function integer($data, $value, $extra=NULL) {
        $params = array('class' => 'intField');
        if (is_array($data)) {
            $data = array_merge($params, $data);
        }
        else {
            $params['name'] = $data;
            $params['id'] = $data;
            $data = $params;
        }
        return form::input($data, $value, $extra);
    }

    public static function decimal($data, $value, $extra=NULL) {
        $params = array('class' => 'decimalField');
        if (is_array($data)) {
            $data = array_merge($params, $data);
        }
        else {
            $params['name'] = $data;
            $params['id'] = $data;
            $data = $params;
        }
        if ($value) {
            // $value = format::decimal($value);
        }
        return form::input($data, $value, $extra);
    }

    public static function selectOneRadio($name, $value, $formData, $extra=NULL) {
        return self::radio($name, $value, $formData[$name] == $value, $extra);
    }

    public static function radioButtonList($formData, $optionList, $fieldName) {
        $html = '';
        $html .= '<ul class="radioButtonList">';
        foreach ($optionList as $value => $label) {
            $html .= '<li>';
            $html .= '<label>' .
                    form::selectOneRadio($fieldName, $value, $formData) .
                    $label .
                    '</label>';
            $html .= '</li>';
        }
        $html .= '</ul>';
        return $html;
    }

    public static function comboBox($name, $options, $formData, $extra=NULL) {
        return self::dropdown($name, $options, $formData[$name], $extra);
    }
    
    public static function radioButton($name, $value, $formData, $extra=NULL) {
        return self::radio($name, $value, $value == $formData[$name], $extra);
    }

    public static function text($name, $formData, $extra=NULL) {
        return self::input($name, $formData[$name], $extra);
    }

    public static function hiddenWithId($nameAndId, $value) {
        $attr = array(
            'type' => 'hidden',
            'id' => $nameAndId,
            'name' => $nameAndId,
            'value' => $value
        );
        return form::input($attr);
    }

    public static function checkboxWithId($name, $id, $value, $formModel, $extra=NULL) {
        $attr = array(
            'type' => 'checkbox',
            'id' => $id,
            'name' => $name,
        );

        $checked = FALSE;
        if (substr($name, -2) == '[]') {
            $valueList = $formModel[substr($name, 0, -2)];
            if (is_array($valueList)) {
                $checked = array_search($value, $valueList) !== FALSE;
            }
        }
        else {
            if ($formModel[$name] == sql::$TRUE) {
                $checked = TRUE;
            }
        }
        
        if ($checked) {
            $attr['checked'] = 'checked';
        }
        
        return form::input($attr, $value, $extra);
    }

    public static function submitButton($labelKey, $image=NULL, $id=NULL) {
        $html = '<button type="submit" onclick="disableButton(this)"' . ($id ? ' id="' . $id . '"': '') . '>';
        if ($image) {
            $html .= html::img($image);
        }
        $html .= text::get('button.' . $labelKey) . '</button>';
        return $html;
    }

    private static function formId() {
        $sessionData = SessionData::instance();
        return '<input type="hidden" name="' . auth::$FORM_ID . '" value="' . $sessionData->createFormId() . '" />';
    }

    public static function open($action = NULL, $attr = array(), $hidden = NULL) {
        $html = parent::open($action, $attr, $hidden);
        if (empty($attr['method']) || strtolower($attr['method']) == 'post') {
            // Every POST request must contain a form ID
            $html .= self::formId();
        }
        return $html;
    }

    public static function selectMany() {
        $html = '<div id="' . $this->fieldId . '" class="selectManyCheckboxes" onclick="selectManyCheckboxesClick(this,event)">';
        foreach ($this->optionList as $value => $label) {
            $selected = FALSE !== array_search($value, $this->selectedValues);
            $html .= '<label';
            if ($selected) {
                $html .= ' class="selected"';
            }
            $html .= '><input type="checkbox" name="' . $this->getInputFieldName() . '[]" value="' . $value . '"';
            if ($selected) {
                $html .= ' checked="checked" ';
            }
            $html .= ' />';
            $html .= $label . '</label>';
        }
        // $html .= html::img('add.png') . '<a href="">Přidej hodnotu</a>';
        $html .= '</div>';
        if ($this->createButton) {
            $dialogName = str_replace('_ids', '', $this->fieldName) . 'Dialog';
            $html .= '<button type="button" onclick="new Dialog(\'' . url::site($this->popupUrl) . '\', \'' . $this->fieldId . '\').open()">' . html::img('add.png') . text::get('button.addNewItem') . '</button>';
        }
    }

    public static function jQueryButton() {
        echo '<button type="button" onclick="closeDialog()" class="ui-priority-secondary ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"><span class="ui-button-text">' . text::getEscaped('button.cancel') . '</span></button>';
    }
    
    
    public static function sortableList($itemList, $displayAttribute, $pkField) {
        $html = '<script>' .
            '$(document).ready(function() {' .
                    '$( ".sortableList" ).sortable().disableSelection();' .
            '});' .
            '</script>';

        $html .= '<ol class="sortableList">';
        foreach ($itemList as $item) {
            $html .= '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' .
                form::checkbox('itemOrder[]', $item[$pkField], TRUE) .
                $item[$displayAttribute] . '</li>';
        }
        $html .= '</ol>';
        return $html;
    }
    
    public static function idcardOptions() {
    	return array(
    			'idcard' => text::get('person-idcard_type-idcard'),
    			'passport' => text::get('person-idcard_type-passport')
    	);
    }
    
    public static function languageOptions() {
    	$languages = Kohana::config('multi_lang.allowed_languages');
    	$options = array();
    	foreach ($languages as $langCode => $locale) {
    		$options[$langCode] = constants::$languageNames[$langCode];
    	}
    	return $options;
    }
    
    public static function currencyOptions() {
    	return array(
    			'CZK' => text::get('currency-mark-CZK'),
    			'EUR' => text::get('currency-mark-EUR')
    	);
    }
    
    /**
     * Adds an empty option at the beginning of the given array if it's not there already and returns it.
     * @param array $options associative array (select options) in value => label format.
     */
    public static function addEmptyOption($options) {
    	if (count($options) > 0) {
    		foreach ($options as $value => $label) {
    			if (! $value) {
    				return $options;
    			}
    			break;
    		}
    	}
    	// Array addition doesn't recalculate keys.
    	return array('' => '') + $options;
    }
}